<?php
require_once('global.php');
require_once(R_P.'require/tool.php');
!$windid && Showmsg('not_login');
list($db_moneyname,$db_moneyunit,$db_rvrcname,$db_rvrcunit,$db_creditname,$db_creditunit)=explode("\t",$db_credits);
$userdb = $db->get_one("SELECT md.postnum,md.digests,md.rvrc,md.money,md.credit,md.currency,mb.deposit,mb.ddeposit FROM pw_memberdata md LEFT JOIN pw_memberinfo mb USING(uid) WHERE md.uid='$winduid'");
require_once(R_P.'require/credit.php');
$creditdb = GetCredit($winduid);
InitGP(array('action'));

if(!$action){
	include_once(D_P.'data/bbscache/ol_config.php');
	if(!$ol_onlinepay){
		Showmsg($ol_whycolse);
	}
	if(!$ol_payto && (!$ol_paypal || !$ol_paypalcode) && (!$ol_99bill || !$ol_99billcode) && (!$ol_tenpay || !$ol_tenpaycode)){
		Showmsg('olpay_seterror');
	}
	require_once(R_P.'require/header.php');
	$rt = $db->get_one("SELECT hk_value FROM pw_hack WHERE hk_name='adminbankinfo'");
	$adminbankinfo = str_replace("\n","<br>",$rt['hk_value']);
	require_once PrintEot('userpay');footer();
} elseif($action == 'pay'){
	include_once(D_P.'data/bbscache/ol_config.php');
	include(GetLang('other'));
	if(!$ol_onlinepay){
		Showmsg($ol_whycolse);
	}
	InitGP(array('number','method'));
	$number = intval($number);
	if(!$number || $number < $db_rmblest){
		Showmsg('olpay_numerror');
	}
	$order_no = ($method-1).str_pad($winduid,10, "0",STR_PAD_LEFT).get_date($timestamp,'YmdHis').num_rand(5);

	$db->update("INSERT INTO pw_clientorder(order_no,uid,subject,body,price,number,date,state,descrip) VALUES('$order_no','$winduid','$lang[currency]','$lang[buy_currency]','1','$number','$timestamp','0','$lang[unpay_list]')");

	if($method==1){
		if(!$ol_paypal || !$ol_paypalcode){
			Showmsg('olpay_paypalerror');
		}
		$url  = "https://www.paypal.com/cgi-bin/webscr?";
		$para = array(
			'cmd'=>'_xclick',
			'invoice'=>$order_no,
			'business'=>$ol_paypal,
			'item_name'=>$lang['buy_currency'],
			'item_number'=>'phpw*',
			'amount'=>$number,
			'no_shipping'=>0,
			'no_note'=>1,
			'currency_code'=>'CNY',
			'bn'=>'phpwind',
			'charset'=>$db_charset
		);
		foreach($para as $key => $value){
			$url .= $key."=".urlencode($value)."&";
		}
		ObHeader($url);
	} elseif($method==2){
		if(!$ol_payto){
			Showmsg('olpay_alipayerror');
		}
		$url  = "http://pay.phpwind.com/pay/create_payurl.php?";
		$para = array(
			'_input_charset' => $db_charset,
			'service' => 'create_direct_pay_by_user',
			'return_url' => "{$db_bbsurl}/alipay.php",
			'payment_type' => '1',
			'subject' => $lang['currency'],
			'body' => $lang['buy_currency'],
			'out_trade_no' => $order_no,
			'total_fee' => $number,
			'seller_email' => $ol_payto,
		);
		$arg='';
		foreach($para as $key => $value){
			if($value){
				$url  .= "$key=".urlencode($value)."&";
			}
		}
		ObHeader($url);
	} elseif($method==3){//fix by noizy
		if (!$ol_99bill || !$ol_99billcode) {
			Showmsg('olpay_pay99error');
		}
		strlen($ol_99bill)==11 && $ol_99bill .= '01';
		require_once(R_P.'require/header.php');
		!$db_rmbrate && $db_rmbrate=10;
		$para = array(
			'inputCharset' => ($db_charset=='gbk' ? 2 : 1),
			'pageUrl' => "{$db_bbsurl}/pay99bill.php",
			'version' => 'v2.0',
			'language' => 1,
			'signType' => 1,
			'merchantAcctId' => $ol_99bill,
			'payerName' => $windid,
			'orderId' => $order_no,
			'orderAmount' => ($number*100),
			'orderTime' => get_date($timestamp,'YmdHis'),
			'productName' => $lang['buy_currency'],
			'productNum' => ($number*$db_rmbrate),
			'payType' => '00',
			'redoFlag' => 1
		);
		$signMsg = $inputMsg = '';
		foreach ($para as $key => $value) {
			$value = trim($value);
			if (strlen($value)>0) {
				$signMsg .= "$key=$value&";
				$inputMsg .= "<input type=\"hidden\" name=\"$key\" value=\"$value\" />";
			}
		}
		$signMsg = strtoupper(md5($signMsg."key=$ol_99billcode"));
		require_once PrintEot('userpay');footer();
	} elseif($method==4){
		if(!$ol_tenpay || !$ol_tenpaycode){
			Showmsg('olpay_tenpayerror');
		}
		$strBillDate= get_date($timestamp,'Ymd');
		$strSpBillNo=substr($order_no,-10);
		$strTransactionId = $ol_tenpay . $strBillDate . $strSpBillNo;
		$db->update("UPDATE pw_clientorder SET order_no='$strTransactionId' WHERE order_no='$order_no'");

//		$url  = "https://www.tenpay.com/cgi-bin/v1.0/pay_gate.cgi?";
		$url  = "http://pay.phpwind.com/pay/create_payurl.php?";
		$para = array(
			'cmdno' => '1',
			'date' => $strBillDate,
			'bargainor_id' => $ol_tenpay,
			'transaction_id' => $strTransactionId,
			'sp_billno' => $strSpBillNo,
			'total_fee' => $number*100,
			'bank_type' => 0,
			'fee_type' => 1,
			'return_url' => "{$db_bbsurl}/tenpay.php",
			'attach' => 'my_magic_string',
		);
		$arg='';
		foreach($para as $key => $value){
			if($value){
				$url .= "$key=".urlencode($value)."&";
				$arg .= "$key=$value&";
			}
		}
		$strSign = strtoupper(md5($arg."key=$ol_tenpaycode"));
		$url .= "desc=$lang[currency]&sign=$strSign";
		ObHeader($url);
	}
} elseif($action == 'list'){
	InitGP(array('state'));
	$sqladd = "WHERE uid='$winduid'";
	if($state == 1){
		$sqladd .= " AND state<2";
	} elseif($state == 2){
		$sqladd .= " AND state=2";
	}
	include_once(R_P.'require/forum.php');
	(!is_numeric($page) || $page < 1) && $page = 1;
	$limit = "LIMIT ".($page-1)*$db_perpage.",$db_perpage";
	$rt    = $db->get_one("SELECT COUNT(*) AS sum FROM pw_clientorder $sqladd");
	$pages = numofpage($rt['sum'],$page,ceil($rt['sum']/$db_perpage),"userpay.php?action=list&state=$state&");

	$query = $db->query("SELECT * FROM pw_clientorder $sqladd ORDER BY date DESC $limit");
	while($rt=$db->fetch_array($query)){
		$rt['date'] = get_date($rt['date']);
		$orderdb[] = $rt;
	}
	require_once(R_P.'require/header.php');
	require_once PrintEot('userpay');footer();
} elseif($action == 'log'){
	InitGP(array('keyword','page'));
	if($keyword){
		$sqladd = " AND descrip LIKE '%$keyword%'";
		$urladd = 'keyword='.rawurlencode($keyword)."&";
	} else{
		$sqladd = $urladd = '';
	}
	require_once(R_P.'require/forum.php');
	require_once(R_P.'require/bbscode.php');
	(!is_numeric($page) || $page<1) && $page = 1;
	$limit = "LIMIT ".($page-1)*$db_perpage.",$db_perpage";
	$rt	= $db->get_one("SELECT COUNT(*) AS sum FROM pw_toollog WHERE uid='$winduid' $sqladd");
	$pages = numofpage($rt['sum'],$page,ceil($rt['sum']/$db_perpage),"userpay.php?action=log&$urladd");

	$query = $db->query("SELECT * FROM pw_toollog WHERE uid='$winduid' $sqladd ORDER BY time DESC $limit");
	while($rt = $db->fetch_array($query)){
		$rt['time']   = get_date($rt['time']);
		$rt['descrip']= convert($rt['descrip'],array());
		$logdb[]	  = $rt;
	}
	require_once(R_P.'require/header.php');
	require_once PrintEot('userpay');footer();
} elseif($action == 'virement'){
	$query = $db->query("SELECT db_name,db_value FROM pw_config WHERE db_name LIKE 'cy\_%'");
	while($rt = $db->fetch_array($query)){
		$$rt['db_name'] = $rt['db_value'];
	}
	!$cy_virement && Showmsg('virement_closed');

	if(!$_POST['step']){
		require_once(R_P.'require/header.php');
		require_once PrintEot('userpay');footer();
	} elseif($_POST['step']==2){
		InitGP(array('pwuser','pwpwd','currency'),'P');
		$rt		= $db->get_one("SELECT uid FROM pw_members WHERE username='$pwuser'");
		$touid	= $rt['uid'];
		if(!$rt){
			$errorname = Char_cv($pwuser);
			Showmsg('user_not_exists');
		}
		$currency = (int)$currency;
		if(!is_numeric($currency) || $currency <= 0){
			Showmsg('illegal_nums');
		}
		if(!$pwpwd){
			Showmsg('empty_password');
		}
		if($cy_virelimit && $currency < $cy_virelimit){
			Showmsg('currency_limit');
		}
		$lockfile = D_P.'data/bbscache/lock_userpay.txt';
		$fp = fopen($lockfile,'wb+');
		flock($fp,LOCK_EX);

		$rt = $db->get_one("SELECT m.password,md.currency FROM pw_members m LEFT JOIN pw_memberdata md USING(uid) WHERE m.uid='$winduid'");
		if(md5($pwpwd) != $rt['password']){
			Showmsg('password_error');
		}
		$tax = round($currency * $cy_virerate/100);
		$needcurrency = $currency + $tax;
		if($rt['currency'] < $needcurrency){
			Showmsg('noenough_currency');
		}
		$db->update("UPDATE pw_memberdata SET currency=currency-'$needcurrency' WHERE uid='$winduid'");
		$db->update("UPDATE pw_memberdata SET currency=currency+'$currency' WHERE uid='$touid'");

		fclose($fp);
		require_once(R_P.'require/tool.php');
		$logdata=array(
			'type'		=>	'vire',
			'nums'		=>	0,
			'money'		=>	0,
			'descrip'	=>	'vire_descrip',
			'uid'		=>	$winduid,
			'username'	=>	$windid,
			'ip'		=>	$onlineip,
			'time'		=>	$timestamp,
			'toname'	=>	$pwuser,
			'currency'	=>	$currency,
			'tax'		=>	$tax
		);
		writetoollog($logdata);
		require_once(R_P.'require/msg.php');
		$message=array(
			$pwuser,
			$winduid,
			'vire_title',
			$timestamp,
			'vire_content',
			'',
			$windid
		);
		writenewmsg($message,1);

		Showmsg('virement_success');
	}
}
?>